package com.yy.permissions_general.common.config.websocket;

import com.yy.permissions_general.utils.FastJsonUtils;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName MessageWebsocket
 * @Description: TODO 消息
 * @Author YangYI
 * @Date 2021/1/21
 * @Version V1.0
 **/
@Component
@ServerEndpoint("/messageWebsocket/{idCard}")
public class MessageWebsocket {
    public static Map<String, Session> messageWebsocketMap = new ConcurrentHashMap(512);

    public MessageWebsocket() {
    }

    @OnOpen
    public void onOpen(@PathParam("idCard") String idCard, Session session) {
        Session onSession = (Session)messageWebsocketMap.get(idCard);
        if (onSession == null) {
            messageWebsocketMap.put(idCard, session);
        }

    }

    @OnClose
    public void onClose(@PathParam("idCard") String idCard, Session session) {
        if (messageWebsocketMap.containsKey(idCard)) {
            messageWebsocketMap.remove(idCard);
        }

    }

    @OnMessage
    public void onMessage(String message, Session session) {
    }

    @OnError
    public void onError(Session session, Throwable error) {
        System.out.println("发生错误" + error.getMessage());
    }


    public void sendMessage(String message){
        try {
            Map<String,Object> map = FastJsonUtils.toMap(message);
            String[] cards = String.valueOf(map.get("idCards")).split(",");
            for (String s : messageWebsocketMap.keySet()) {
                for (String card : cards) {
                    if (s.equals(card)){
                        Session onSession = (Session)messageWebsocketMap.get(card);
                        onSession.getBasicRemote().sendText(message);
                    }
                }
            }
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
}
